package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.impl.UserServiceInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserServiceInterface userServiceInterface;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping
    public User save(@RequestBody User parameter) {
        User user = new User();
        user.setUsername(parameter.getUsername());
        user.setPassword(bCryptPasswordEncoder.encode(parameter.getPassword()));
        if("admin".equals(parameter.getUsername())){
            user.setRole("ADMIN");
        }else{
            user.setRole("USER");
        }
        return userServiceInterface.save(user);
    }

    @GetMapping
    public User findByUsername(@RequestParam String username){
        return userServiceInterface.findByUsername(username);
    }

    @GetMapping("/findAll")
    @PreAuthorize("hasAnyAuthority('ADMIN')")  //这一步很重要 拥有ADMIN权限的用户才能访问该请求
    public List<User> findAll(){
        return userServiceInterface.findAll();
    }

}
